//
//  CityListViewController.m
//  ChinaCityList
//
//  Created by zjq on 15/10/27.
//  Copyright © 2015年 zhengjq. All rights reserved.
//
#import "CityListViewController.h"
#import "ZYPinYinSearch.h"
#import "ButtonGroupView.h"
#import "PinYinForObjc.h"
#import "CTCollectionViewCell.h"

#import "XXTripTableViewController.h"
#import "TravelDateViewController.h"
#import "HomeViewController.h"
#import "CountyCityViewController.h"
#define KSectionIndexBackgroundColor  [UIColor clearColor] //索引试图未选中时的背景颜色
#define kSectionIndexTrackingBackgroundColor [UIColor lightGrayColor]//索引试图选中时的背景
#define kSectionIndexColor [UIColor grayColor]//索引视图字体颜色
#define HotBtnColumns 3 //每行显示的热门城市数
#define BGNAVCOLOR [UIColor colorWithRed:240/255.0 green:240/255.0 blue:240/255.0 alpha:1]
@interface CityListViewController ()<UIGestureRecognizerDelegate,UISearchBarDelegate,UITextFieldDelegate,ButtonGroupViewDelegate,UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout>
{
    UIImageView   *_bgImageView;
    UIView        *_tipsView;
    UILabel       *_tipsLab;
    NSTimer       *_timer;
    
    NSMutableArray *arrAddCityValue;    // 用来添加所有的市级
    NSMutableArray *arrAddTownArrValue; // 用来添加所有的市级对应的县级数组
    NSMutableArray * provinceCityArr;   // 装载各个省份所包含的城市的二维数组arr[省][市]
    NSDictionary * dicAllValue;         // 得到Plist文件中所有的数据
    
    NSString    *_city;
    
    UIButton    *_btn;
    
    UICollectionView    *_collectionView;
    
    NSArray     *_arrTown;
    
    NSString  *_area;
    
    UIView      *_backView;
    UIView      *alphaView;
    
    UILabel  *_cityLabel;
    
    NSString * _transformCityName;
    
    BOOL isCollcetionHidden;    //判断是定位还是选择行程
}
@property (strong, nonatomic) UITextField *searchText;

@property (strong, nonatomic) NSMutableDictionary *searchResultDic;

@property (strong, nonatomic) ButtonGroupView *locatingCityGroupView;//定位城市试图

@property (strong, nonatomic) ButtonGroupView *hotCityGroupView;//热门城市

@property (strong, nonatomic) ButtonGroupView *historicalCityGroupView; //历史使用城市/常用城市

@property (strong, nonatomic) UIView *tableHeaderView;

@property (strong, nonatomic) NSMutableArray *arrayCitys;  //城市数据

@property (strong, nonatomic) NSMutableDictionary *cities;

@property (strong, nonatomic) NSMutableArray *keys; //城市首字母

@property (nonatomic, strong)UIViewController * lastVC;
@end

@implementation CityListViewController

- (id)init
{
    self = [super init];
    if (self) {
        // Custom initialization
        self.arrayHotCity = [NSMutableArray array];
        
        self.arrayHistoricalCity = [NSMutableArray array];
        
        self.arrayLocatingCity   = [NSMutableArray array];
        self.keys = [NSMutableArray array];
        self.arrayCitys = [NSMutableArray array];
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.navigationItem.title = @"选择城市";
    [self loadAndDealWithData];
    self.view.backgroundColor=[UIColor whiteColor];
//    [self getCityData];
    
    //tableView
    _tableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];
    _tableView.frame           = CGRectMake(0,0, self.view.frame.size.width, self.view.frame.size.height-64);
    _tableView.backgroundColor = [UIColor clearColor];
    _tableView.delegate        = self;
    _tableView.dataSource      = self;
    [self.view addSubview:_tableView];
    
    
    NSArray *vcsArray = [self.navigationController viewControllers];
    NSInteger vcCount = vcsArray.count;
    _lastVC = vcsArray[vcCount-2];
    if ([_lastVC isKindOfClass:[HomeViewController class]]) {
        isCollcetionHidden = YES;
    }else{
        isCollcetionHidden = NO;
        [self ininHeaderView];
    }
    
    UICollectionViewFlowLayout *layout=[[UICollectionViewFlowLayout alloc]init];
    _collectionView=[[UICollectionView alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(_backView.frame), self.view.frame.size.width, 170) collectionViewLayout:layout];
    _collectionView.delegate=self;
    _collectionView.dataSource=self;
      [_collectionView registerNib:[UINib nibWithNibName:@"CTCollectionViewCell" bundle:nil] forCellWithReuseIdentifier:@"CTcell"];
    _collectionView.backgroundColor=[UIColor whiteColor];

    //黑色透明背景
    alphaView=[[UIView alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(_backView.frame), self.view.frame.size.width, self.view.frame.size.height)];
    alphaView.backgroundColor=[UIColor blackColor];
    alphaView.alpha=0.4;

}

-(void)areaClick:(UIButton*)button
{
    if (_isOpen==NO)
    {
        [button setImage:[UIImage imageNamed:@"icon_pull_up"] forState:UIControlStateNormal];
        [self.view addSubview:alphaView];
        [self.view addSubview:_collectionView];
        [_collectionView reloadData];
        _isOpen=YES;
    }
    else
    {
        [button setImage:[UIImage imageNamed:@"icon_pull_down"] forState:UIControlStateNormal];
        [alphaView removeFromSuperview];
        [_collectionView removeFromSuperview];
        _isOpen=NO;
        
    }
    
}


-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{

    return _arrTown.count;
}

-(UICollectionViewCell*)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
      CTCollectionViewCell *cell=[collectionView dequeueReusableCellWithReuseIdentifier:@"CTcell" forIndexPath:indexPath];
    cell.layer.borderColor=[[[UIColor lightGrayColor]colorWithAlphaComponent:0.5]CGColor];
    cell.layer.borderWidth=1;
   cell.textLabel.text=[_arrTown objectAtIndex:indexPath.item];
    return cell;
    
}

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    _area=[_arrTown objectAtIndex:indexPath.item];
    [alphaView removeFromSuperview];
    [collectionView removeFromSuperview];
    _isOpen=NO;
    [_btn setImage:[UIImage imageNamed:@"icon_pull_down"] forState:UIControlStateNormal];
    
    if ([_delegate respondsToSelector:@selector(didSelectedWithAreaName:)])
    {
    
        [_delegate didSelectedWithAreaName:_area];
    }
    TravelDateViewController *vc = [[TravelDateViewController alloc]init];
    [self.navigationController pushViewController:vc animated:YES];
    
}

-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{

   return CGSizeMake(100, 40);
    
}

-(UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{

    return UIEdgeInsetsMake(20, 20, 0, 20);
    
}

- (void)setNavigationWithTitle:(NSString *)title
{
    //自定义导航栏
    UIView *customNavView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 64)];
    customNavView.backgroundColor = BGNAVCOLOR;
    
    UIButton *backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [backBtn setImage:[UIImage imageNamed:@"guanbiSmall"] forState:UIControlStateNormal];
    backBtn.frame = CGRectMake(20, 27, 30, 30);
    [backBtn addTarget:self action:@selector(back:) forControlEvents:UIControlEventTouchUpInside];
    [customNavView addSubview:backBtn];
    UILabel *titleLab = [[UILabel alloc]initWithFrame:CGRectMake(0, 20, customNavView.frame.size.width, customNavView.frame.size.height-20)];
    titleLab.textAlignment = NSTextAlignmentCenter;
    titleLab.text          = title;
    [customNavView addSubview:titleLab];
    
    
    [self.view addSubview:customNavView];
}

- (void)back:(UIButton*)sender
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)ininHeaderView
{
    _tableHeaderView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, _tableView.frame.size.width, 250)];
    _tableHeaderView.backgroundColor = [UIColor clearColor];

    //定位城市
    UILabel *title1 = [[UILabel alloc]initWithFrame:CGRectMake(10, 10, 160, 21)];
    title1.text = @"当前定位";
    title1.font = [UIFont systemFontOfSize:15];
    [_tableHeaderView addSubview:title1];
    
    _locatingCityGroupView = [[ButtonGroupView alloc]initWithFrame:CGRectMake(0, title1.frame.origin.y+title1.frame.size.height+10, _tableHeaderView.frame.size.width, 45)];
    _locatingCityGroupView.delegate = self;
    _locatingCityGroupView.columns = 3;
    _locatingCityGroupView.items = [self GetCityDataSoucre:_arrayLocatingCity];
    [_tableHeaderView addSubview:_locatingCityGroupView];
    
    UILabel *title3 = [[UILabel alloc]initWithFrame:CGRectMake(10, _locatingCityGroupView.frame.origin.y+_locatingCityGroupView.frame.size.height+10, 160, 21)];
    title3.text = @"热门城市";
    title3.font = [UIFont systemFontOfSize:15];
    [_tableHeaderView addSubview:title3];
    
    
    long row = _arrayHotCity.count/3;
    if (_arrayHotCity.count%3 > 0) {
        row += 1;
    }
    CGFloat hotViewHight = 45*row;
    _hotCityGroupView = [[ButtonGroupView alloc]initWithFrame:CGRectMake(0, title3.frame.origin.y+title3.frame.size.height+10, _tableHeaderView.frame.size.width, hotViewHight)];
    _hotCityGroupView.backgroundColor = [UIColor clearColor];
    _hotCityGroupView.delegate = self;
    _hotCityGroupView.columns = 3;
    _hotCityGroupView.items = [self GetCityDataSoucre:_arrayHotCity];
    [_tableHeaderView addSubview:_hotCityGroupView];
    
    _tableHeaderView.frame = CGRectMake(0, 0, _tableView.frame.size.width, _hotCityGroupView.frame.origin.y+_hotCityGroupView.frame.size.height);
    _tableView.tableHeaderView.frame = _tableHeaderView.frame;
    _tableView.tableHeaderView = _tableHeaderView;
    
    _tableHeaderView.height = 0;
    _hotCityGroupView.hidden = YES;
    _locatingCityGroupView.hidden = YES;
    title1.hidden = YES;
    title3.hidden = YES;
}

- (NSArray*)GetCityDataSoucre:(NSArray*)ary
{
    NSMutableArray *cityAry = [[NSMutableArray alloc]init];
    for (NSString*cityName in ary) {
        [cityAry addObject: [CityItem initWithTitleName:cityName]];
    }
    
    return cityAry;
}

#pragma mark - tableView
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 20.0;
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *bgView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, tableView.frame.size.width, 20)];
    bgView.backgroundColor = BGNAVCOLOR;

    UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(13, 0, 250, 20)];
    titleLabel.backgroundColor = [UIColor clearColor];
    titleLabel.textColor = [UIColor blackColor];
    titleLabel.font = [UIFont systemFontOfSize:15];

    UIImageView *line = [[UIImageView alloc]initWithFrame:CGRectMake(0, 19, bgView.frame.size.width, 1)];
    line.backgroundColor = [UIColor colorWithRed:220/255.0 green:220/255.0 blue:220/255.0 alpha:1];
    NSString *key = [_arrTown objectAtIndex:section];

    titleLabel.text = key;
    [bgView addSubview:line];

    [bgView addSubview:titleLabel];

    return bgView;
}

- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView
{
    NSMutableArray *indexNumber = [NSMutableArray arrayWithArray:_arrTown];
    return indexNumber;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return [_arrTown count];
}

- (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index
{
    [self showTipsWithTitle:title];
    return index;
}

- (void)showTipsWithTitle:(NSString*)title
{
    
    //获取当前屏幕window
    UIWindow *window = [UIApplication sharedApplication].keyWindow;
    if (!_tipsView) {
        //添加字母提示框
        _tipsView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 80, 80)];
        _tipsView.center = window.center;
        _tipsView.backgroundColor = [UIColor colorWithRed:0.95 green:0.95 blue:0.95 alpha:0.8];
        //设置提示框圆角
        _tipsView.layer.masksToBounds = YES;
        _tipsView.layer.cornerRadius  = _tipsView.frame.size.width/20;
        _tipsView.layer.borderColor   = [UIColor whiteColor].CGColor;
        _tipsView.layer.borderWidth   = 2;
        [window addSubview:_tipsView];
    }
    if (!_tipsLab) {
        //添加提示字母lable
        _tipsLab = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, _tipsView.frame.size.width, _tipsView.frame.size.height)];
        //设置背景为透明
        _tipsLab.backgroundColor = [UIColor clearColor];
        _tipsLab.font = [UIFont boldSystemFontOfSize:50];
        _tipsLab.textAlignment = NSTextAlignmentCenter;
        
        [_tipsView addSubview:_tipsLab];
    }
   _tipsLab.text = title;//设置当前显示字母
    
    _timer = [NSTimer timerWithTimeInterval:1 target:self selector:@selector(hiddenTipsView) userInfo:nil repeats:NO];
    [[NSRunLoop mainRunLoop] addTimer:_timer forMode:NSRunLoopCommonModes];
    
}

- (void)hiddenTipsView
{
    
    [UIView animateWithDuration:0.2 animations:^{
        _bgImageView.alpha = 0;
        _tipsView.alpha = 0;
    } completion:^(BOOL finished) {
        [_bgImageView removeFromSuperview];
        [_tipsView removeFromSuperview];
         _bgImageView = nil;
         _tipsLab     = nil;
         _tipsView    = nil;
    }];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [provinceCityArr[section] count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    if ([_tableView respondsToSelector:@selector(setSectionIndexColor:)]) {
        _tableView.sectionIndexBackgroundColor = KSectionIndexBackgroundColor;  //修改索引试图未选中时的背景颜色
        _tableView.sectionIndexTrackingBackgroundColor = kSectionIndexTrackingBackgroundColor;//修改索引试图选中时的背景颜色
        _tableView.sectionIndexColor = kSectionIndexColor;//修改索引试图字体颜色
    }
    
    
    static NSString *CellIdentifier = @"Cell";
    
//    NSString *key = [_arrTown objectAtIndex:indexPath.section];
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] ;
        cell.backgroundColor = [UIColor clearColor];
        cell.contentView.backgroundColor = [UIColor clearColor];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        [cell.textLabel setTextColor:[UIColor blackColor]];
        cell.textLabel.font = [UIFont systemFontOfSize:18];
    }
    
    cell.textLabel.text = [[provinceCityArr objectAtIndex:indexPath.section] objectAtIndex:indexPath.row];
    return cell;
}

#pragma mark 点击了对应的Cell
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(nonnull NSIndexPath *)indexPath
{
    for (int i = 0; i<[[dicAllValue allValues] count]; i++) {
        for (int y = 0; y<[[dicAllValue allValues][i] count]; y++) {
            NSDictionary * dic = [dicAllValue allValues][i][y];
            for (NSArray * arr in dic) {
                if ([provinceCityArr[indexPath.section][indexPath.row] isEqualToString:arr]) {
                    NSLog(@"%@", [dic objectForKey:arr]);
                    if ([[dic objectForKey:arr] count] > 1) {
                        CountyCityViewController * countyCityVC = [[CountyCityViewController alloc] init];
                        countyCityVC.title = provinceCityArr[indexPath.section][indexPath.row];
                        countyCityVC.countyCityArr = [dic objectForKey:arr];
                        countyCityVC.isCollectionHidden = isCollcetionHidden;
                        [self.navigationController pushViewController:countyCityVC animated:YES];
                    }else{
                        CountyCityViewController * countyCityVC = [[CountyCityViewController alloc] init];
                        countyCityVC.title = provinceCityArr[indexPath.section][indexPath.row];
                        countyCityVC.countyCityArr = [NSArray arrayWithObject:provinceCityArr[indexPath.section][indexPath.row]];
                        countyCityVC.isCollectionHidden = isCollcetionHidden;
                        [self.navigationController pushViewController:countyCityVC animated:YES];
                    }
                }
            }

        }
    }
}

#pragma mark 点击了上面的Item
-(void)ButtonGroupView:(ButtonGroupView *)buttonGroupView didClickedItem:(CityButton *)item
{
    if (_delegate) {
       
        [_delegate didClickedWithCityName:item.cityItem.titleName];
        [self showFinaTownData:item.cityItem.titleName];
         _cityLabel.text=[NSString stringWithFormat:@"当前:%@全城",item.cityItem.titleName];
    }
    _transformCityName = item.cityItem.titleName;
    TravelDateViewController *vc = [[TravelDateViewController alloc]init];
    vc.city = _transformCityName;
    [self.navigationController pushViewController:vc animated:YES];
}

NSInteger cityNameSort(id str1, id str2, void *context)
{
    NSString *string1 = (NSString*)str1;
    NSString *string2 = (NSString*)str2;
    
    return  [string1 localizedCompare:string2];
}

#pragma mark 加载和处理数据
-(void)loadAndDealWithData{
    
    NSString *loadPath=[[NSBundle mainBundle]pathForResource:@"Address.plist" ofType:nil];
    dicAllValue=[NSDictionary dictionaryWithContentsOfFile:loadPath]; // 得到Plist文件中所有的数据
    // 下面是处理数据
    NSArray *arrAllCityAndTownData=[dicAllValue allValues]; // 得到市级和市级对应的所有县级数据,去除省份
    arrAddCityValue=[NSMutableArray array];  // 用来添加所有的市级
    arrAddTownArrValue=[NSMutableArray array]; // 用来添加所有的市级对应的县级数组
    provinceCityArr=[NSMutableArray array];  // 装载各个省份所包含的城市的二维数组arr[省][市]
    _arrTown = [dicAllValue allKeys];//_arrTown为组头
    for (NSArray *arrValue in arrAllCityAndTownData) {
        for (NSDictionary *dicValue in arrValue) {
            if ([dicValue isKindOfClass:[NSDictionary class]]) {
                NSArray *allKey=[dicValue allKeys];
                [provinceCityArr addObject:allKey];
                for (NSString *stringKey in allKey) {
                    [arrAddCityValue addObject:stringKey];
                    NSArray *arrTown=dicValue[stringKey];
                    [arrAddTownArrValue addObject:arrTown];
                }
            }
        }
    }
//    NSDictionary * tempDic = [dicAllValue objectForKey:@"湖北省"][0];
//    NSArray * arreaStrArr = [tempDic objectForKey:@"武汉市"];

    
//    NSLog(@"最终的城市数组::%@ 最终的县级数组:%@",arrAddCityValue,arrAddTownArrValue);
}
#pragma mark 得到对应的县级数组数据
-(void)showFinaTownData:(NSString *)strValueWithCity{
    
    NSInteger cityIndexNum; // 得到对应的城市的下标
    for (NSInteger i=0; i<arrAddCityValue.count; i++)
    {
        NSString *cityValue=arrAddCityValue[i];
        if ([cityValue rangeOfString:strValueWithCity].location!=NSNotFound||[strValueWithCity rangeOfString:cityValue].location!=NSNotFound)
        {
            cityIndexNum=i;
            break;
        }
    }
    if (cityIndexNum>=arrAddTownArrValue.count) return;
   _arrTown=arrAddTownArrValue[cityIndexNum];
  //  NSLog(@"显示对应的县级:%@",_arrTown);
}

@end
